<template>
  <div class="flowpath-container">
    <div>
      <div class="mb20">
        <span class="color_494949 ft12 pr5">{{ translate('关键字') }}：</span>
        <el-input
          v-model="searchInfo"
          class="w164 mr10"
          :placeholder="translate('请输入关键字')"
        />
        <el-button class="settingBtn mr10" type="primary" @click="getList">
          {{ translate('查询') }}
        </el-button>
      </div>
      <div class="add">
        <el-button
          v-if="MenuAuths('add')"
          class="settingBtn"
          type="primary"
          @click="addFn"
          plain
        >
          {{ translate('新增') }}
        </el-button>
        <el-button
          v-if="MenuAuths('add')"
          class="settingBtn"
          type="primary"
          @click="download"
          plain
        >
          {{ translate('导出') }}
        </el-button>
      </div>
      <el-table :data="tableData" v-loading="loading">
        <!-- <el-table-column label="序号" type="index" width="80" /> -->
        <!-- <el-table-column :label="translate('入库单名称')" prop="FullName" /> -->
        <!-- <el-table-column label="库点名称" prop="WHName" show-overflow-tooltip /> -->
        <el-table-column :label="translate('物资计划单号')" width="150">
          <template #default="{ row }">
            <div>
              <span class="iconcolor">{{ row.PlanNo }}</span>
              <vab-icon icon="file-copy-line" @click="copyToClipboard(row.PlanNo)" />
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column :label="translate('物资计划名称')" prop="PlanName" /> -->
        <!-- <el-table-column :label="translate('来源单据号')" prop="SourceBillNo" /> -->
        <el-table-column :label="translate('凭证类型')" prop="VoucherType">
          <template #default="{ row }">
            <div>
              {{ row.VoucherType }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          :label="translate('工厂')"
          prop="Factory"
          show-overflow-tooltip
        />
        <el-table-column
          :label="translate('供货工厂')"
          prop="SupFactory"
          show-overflow-tooltip
        />
        <el-table-column
          :label="translate('科目分配类别')"
          prop="SubjectCate"
          show-overflow-tooltip
        />
        <el-table-column
          :label="translate('采购组')"
          prop="PurchaseGroup"
          show-overflow-tooltip
        />
        <el-table-column
          :label="translate('交货时间')"
          prop="DeliveryDate"
          show-overflow-tooltip
        />
        <el-table-column
          :label="translate('成本中心')"
          prop="CostCenter"
          show-overflow-tooltip
        />
        <el-table-column
          :label="translate('WBS元素')"
          prop="WBSele"
          show-overflow-tooltip
        />
        <el-table-column
          :label="translate('投资名称')"
          prop="InvestName"
          show-overflow-tooltip
        />
        <el-table-column
          :label="translate('技术标准')"
          prop="TechLevel"
          show-overflow-tooltip
        />
        <el-table-column :label="translate('审核状态')">
          <template #default="{ row }">
            <div>
              <el-tag type="success" v-if="row.Remark === '已审核'">{{ row.Remark }}</el-tag>
              <el-tag type="danger" v-if="row.Remark === '已结束'">{{ row.Remark }}</el-tag>
              <el-tag type="info" v-if="row.Remark && row.Remark !== '已审核' && row.Remark !== '已结束'">{{ row.Remark }}</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column :label="translate('操作')" width="300">
          <template #default="{ row }">
            <el-button plain size="small" type="primary" @click="examineFn(row)">
              {{ translate('审核') }}
            </el-button>
            <el-button
              v-if="MenuAuths('edit')"
              plain
              size="small"
              type="primary"
              @click="detailFn(row)"
            >
              {{ translate('编辑') }}
            </el-button>
            <el-button plain size="small" type="primary" @click="print(row)">
              {{ translate('打印') }}
            </el-button>

            <el-button
              v-if="MenuAuths('delete') && row.Remark !== '已审核'"
              plain
              size="small"
              type="danger"
              @click="deletedFn(row)"
            >
              {{ translate('删除') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          :current-page="pageNo"
          :layout="layout"
          :page-size="pageSize"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>
    <el-dialog
      v-model="dialogVisible"
      :title="translate('物资计划上报详情')"
      width="1220px"
      @close="closeFn"
      :close-on-click-modal="false"
    >
      <i v-if="status === 1" class="iconfont icon-shenhezhong iconcommon"></i>
      <i v-if="status === 2" class="iconfont icon-yishenhe iconcommon2"></i>
      <detail
        :agreementlist="agreementList"
        :chileddetail="chileddetail"
        :form="form"
        fromtype="goodslist"
        :purchaselist="PurchaseList"
        :supplierdata="SupplierData"
        :whdata="WHdata"
        @changelist="changeList"
        @deletedchild="deletedchild"
      />
      <template #footer>
        <el-button @click="dialogVisible = false">
          {{ translate('取消') }}
        </el-button>
        <el-button :disabled="isclick" type="primary" @click="submit">
          {{ translate('确定') }}
        </el-button>
      </template>
    </el-dialog>
    <!-- 打印页面 -->
    <el-dialog v-model="isPrint" center width="1350px" @close="isPrint = false" :close-on-click-modal="false">
      <print
        ref="tableRef"
        :chileddetail="chileddetail"
        :form="form"
        fromprint="goodsList"
        :supplierdata="SupplierData"
      />
      <template #footer>
        <el-button @click="isPrint = false">{{ translate('取消') }}</el-button>
        <el-button type="primary" @click="submitPrint">
          {{ translate('打印') }}
        </el-button>
      </template>
    </el-dialog>
    <wordflow
      :drawershow="isdrawershow"
      :formid="formId"
      :nodelist="nodeList"
      @handclose="handleClose"
    />
  </div>
</template>

<script>
  import {
    Wms_planGetPageData,
    PlanDelData,
    Wms_planUpdateData,
    Wms_planAddData,
    Wms_planGetDetailPageData,
    agreePageData,
    Wms_PurchaseList,
    startflow,
    auditwms,
    getinstance,
    WHGetPageData,
    Wms_ItemPlanDown,
  } from '@/api/form'
  import { BaseGetPageData } from '@/api/item'
  import detail from './components/detail'
  import wordflow from '@/views/components/wordflow/index'
  import print from './components/print'
  import { MenuAuth } from '~/src/utils/permission'
  import VabPrint from '@/plugins/VabPrint'
  import { translate } from '@/i18n'
  import { parseTime } from '@/utils'
  export default defineComponent({
    name: 'Flowpath',
    components: { detail, wordflow, print },
    data() {
      return {
        tableData: [],
        searchInfo: '',
        total: 0,
        pageNo: 1,
        pageSize: 20,
        dialogVisible: false,
        enabled: 0,
        DetailPageData: {},
        chileddetail: [],
        isclick: false,
        SupplierData: [
          {
            FullName: '敦煌仓储中心',
          },
          {
            FullName: '格尔木仓储中心',
          },
          {
            FullName: '花土沟仓储中心',
          },
        ], // 供货商单位
        submitType: 'add',
        layout: 'total, sizes, prev, pager, next, jumper',
        deleList: [],
        MenuAuths: '',
        tableRef: null,
        isPrint: false,
        loading: false,
        agreementList: [],
        PurchaseList: [],
        isdrawershow: false,
        nodeList: {},
        formId: '',
        status: -1,
        WHdata: [],
        IPMID: '',
        form: {
          IBType: '',
          InComeNo: '',
          AcceptanceNo: '',
          SourceBillNo: '',
          Supplier: '',
          CCode: '',
          EntrustNo: '',
          CustomizeNo: '',
          ProjectName: '',
          WorkBillNo: '',
          AcceptanceConclusion: '',
          CategoryNumber: '',
          InComeDate: '',
          PurchaseNo: '',
          Description: '',
          Documenter: '',
          MaterialReceiver: '',
          FinancialReviewer: '',
        },
        rules: {
          code: [
            {
              required: true,
              trigger: 'blur',
              message: translate('请输入工号'),
            },
          ],
          Account: [
            {
              required: true,
              trigger: 'blur',
              message: translate('请输入登录账号'),
            },
          ],
          workFlowName: [
            {
              required: true,
              trigger: 'blur',
              message: translate('请输入账号名称'),
            },
          ],
        },
      }
    },
    created() {
      this.MenuAuths = MenuAuth
      this.getList()
    },
    methods: {
      //复制标识
      async copyToClipboard(val) {
        if (navigator.clipboard && window.isSecureContext) {
          try {
          console.log(navigator.clipboard)
          console.log(window.isSecureContext)
          await navigator.clipboard.writeText(val)
          this.$message({
            message:'复制成功',
            type:'success',
          })
          } catch (err) {
            this.$message({
            message:'复制失败',
            type:'error',
          })
          }

        }else {
          // 创建text area
        const textArea = document.createElement("textarea")
        textArea.value = val
        // 使text area不在viewport，同时设置不可见
        textArea.style.position = "absolute"
        textArea.style.opacity = 0
        textArea.style.left = "-999999px"
        textArea.style.top = "-999999px"
        document.body.appendChild(textArea)
        textArea.focus()
        textArea.select()

        return new Promise((res, rej) => {
          // 执行复制命令并移除文本框
          document.execCommand("copy") ? res() : rej()
          textArea.remove()
        }).then(() => {
          this.$message({
              message: "复制成功",
              type: "success",
            })
          }).catch((err) => {
            this.$message({
              message: "复制失败",
              type: "error",
            })
          })
        }

      },
      // 下载物资表
      async download() {
        const params = {
          pageNo: this.pageNo,
          pageSize: this.pageSize,
          tableName: '',
          sort: '',
          order: '',
          wheres: JSON.stringify([
            { name: 'PlanNo', value: this.searchInfo, displayType: 'like' },
          ]),
          export: false,
          value: '',
        }
        const data = await Wms_ItemPlanDown(params)
        const time = parseTime(new Date().getTime(), '{y}{m}{d}{h}{i}{s}')
        const blob = new Blob([data])
        const url = URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.download = `物资计划上报${time}.xlsx`
        link.href = url
        link.click()
      },
      translate(row) {
        return translate(row)
      },
      handleClose() {
        this.isdrawershow = false
      },
      async examineFn(row) {
        const params = {
          keyValue: row.IPMID,
          code: 'Wms_ItemPlanBillMaster',
          formUrl: 'outboundBill',
          flowData: null,
        }
        const data = await startflow(params)
        if (data.code === '200') {
          // this.auditwms('Wms_IncomeBillMaster', row.IBMID)
          this.formId = row.IPMID
          this.$router.push({
            path: '/table/detail',
            query: {
              formId: this.formId,
              formcode: 'Wms_ItemPlanBillMaster',
            },
          })
        } else {
          this.$message({
            message: data.message,
            type: 'error',
          })
        }
      },
      async auditwms(Code, id) {
        const params = {
          code: Code,
          keyValue: id,
        }
        const data = await auditwms(params)
        if (data.code === '200') {
          this.nodeList = data.data
          this.isdrawershow = true
        } else {
          this.$message({
            message: data.message,
            type: 'error',
          })
        }
      },
      async print(row) {
        this.form = row
        this.IPMID = row.IPMID
        await this.Wms_planGetDetailPageData()
        // await this.BaseGetPageData()
        this.isPrint = true
      },
      async submitPrint() {
        await VabPrint(this.$refs.tableRef)
      },
      changeList(val) {
        this.chileddetail = val?.PurchaseOrderDetail
        this.form = {
          IBType: val.IBType,
          InComeNo: val.InComeNo,
          AcceptanceNo: val.AcceptanceNo,
          SourceBillNo: val.SourceBillNo,
          Supplier: val.Supplier,
          CCode: val.CCode,
          EntrustNo: val.EntrustNo,
          CustomizeNo: val.CustomizeNo,
          ProjectName: val.ProjectName,
          WorkBillNo: val.WorkBillNo,
          AcceptanceConclusion: val.AcceptanceConclusion,
          CategoryNumber: val.CategoryNumber,
          InComeDate: val.InComeDate,
          PurchaseNo: val.PurchaseNo,
          Description: val.Description,
          Documenter: val.Documenter,
          MaterialReceiver: val.MaterialReceiver,
          FinancialReviewer: val.FinancialReviewer,
        }
      },
      async Wms_PurchaseList() {
        const params = {
          pageNo: this.pageNo,
          pageSize: this.pageSize,
          tableName: '',
          sort: '',
          order: '',
          wheres: '',
          export: true,
          value: '',
        }
        const data = await Wms_PurchaseList(params)
        if (data.code === '200') {
          this.PurchaseList = data.data.rows
        }
      },
      async getList() {
        this.loading = true
        const params = {
          pageNo: this.pageNo,
          pageSize: this.pageSize,
          tableName: '',
          sort: '',
          order: '',
          wheres: JSON.stringify([
            { name: 'PlanNo', value: this.searchInfo, displayType: 'like' },
          ]),
          export: false,
          value: '',
        }
        const data = await Wms_planGetPageData(params)
        this.tableData = data.data.rows
        this.total = data.data.total
        this.loading = false
        console.log(this.tableData)
      },
      deletedchild(e) {
        this.deleList = e
        console.log(e)
      },
      async deletedFn(row) {
        this.$confirm(translate('确认删除该文件吗?'), translate('提示'), {
          confirmButtonText: translate('确定'),
          cancelButtonText: translate('取消'),
          type: 'warning',
        })
          .then(() => {
            this.deleted(row)
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: translate('已取消删除'),
            })
          })
      },
      async deleted(row) {
        const IbmID = []
        IbmID.push(row.IPMID)
        const params = IbmID
        const data = await PlanDelData(params)
        if (data.code == '200') {
          this.$message({
            message: translate('删除成功'),
            type: 'success',
          })
          await this.getList()
        }
      },
      async agreePageData() {
        const params = {
          pageNo: this.pageNo,
          pageSize: this.pageSize,
          tableName: '',
          sort: '',
          order: '',
          wheres: '',
          export: true,
          value: '',
        }
        const data = await agreePageData(params)
        this.agreementList = data.data.rows
      },
      //分页条数切换
      handleSizeChange(val) {
        this.pageSize = val
        this.getList()
      },
      //分页切换
      handleCurrentChange(val) {
        this.pageNo = val
        this.getList()
      },
      async addFn() {
        this.submitType = 'add'
        this.status = -1
        this.form = {
          IBType: '',
          InComeNo: '',
          AcceptanceNo: '',
          SourceBillNo: '',
          Supplier: '',
          CCode: '',
          EntrustNo: '',
          CustomizeNo: '',
          ProjectName: '',
          WorkBillNo: '',
          AcceptanceConclusion: '',
          CategoryNumber: '',
          InComeDate: '',
          PurchaseNo: '',
          Description: '',
          Documenter: '',
          MaterialReceiver: '',
          FinancialReviewer: '',
        }
        // await this.BaseGetPageData()
        // await this.agreePageData()
        // await this.Wms_PurchaseList()
        this.chileddetail = []
        this.dialogVisible = true
        this.deleList = []
      },
      submit() {
        if (this.status === 1 || this.status === 2) {
          const messages =
            this.status === 1
              ? '单据审核中，不允许修改！'
              : '单据已审核，不允许修改'
          this.$message({
            message: messages,
            type: 'warning',
          })
          return
        }
        if (this.submitType === 'add') {
          this.AddData()
        } else {
          this.updataSaveList()
        }
      },
      closeFn() {
        this.enabled = 0
        this.form.WorkFlowID = ''
      },
      async detailFn(row) {
        this.deleList = []
        this.form = row
        this.IPMID = row.IPMID
        this.submitType = 'edit'
        await this.getinstances(row)
        await this.Wms_planGetDetailPageData()
        // await this.BaseGetPageData()
        // await this.agreePageData()
        // await this.Wms_PurchaseList()
        await this.WHGetPageData()
        this.dialogVisible = true
      },
      async WHGetPageData() {
        const params = {
          pageNo: 1,
          pageSize: 20,
          wheres: `[{"name":"ModuleId","value":"","displayType":"equal"}]`,
          export: true,
          moduleType: 'ModuleId',
          sort: 'SortCode',
          order: 'ASC',
          search: '',
        }
        const data = await WHGetPageData(params)
        if (data.data.rows && data.data.rows.length > 0) {
          data.data.rows.map((item) => {
            item.value = item.FullName
          })
        }
        this.WHdata = data.data.rows
      },
      async getinstances(row) {
        const params = {
          code: 'Wms_ItemPlanBillMaster',
          formId: row.IPMID,
        }
        const data = await getinstance(params)
        if (data.code === '200') {
          this.status = data.data?.data?.status
        }
      },
      async BaseGetPageData() {
        const params = {
          pageNo: 1,
          pageSize: 100,
          tableName: '',
          sort: '',
          order: '',
          wheres: '',
          export: true,
          value: '',
        }
        const data = await BaseGetPageData(params)
        this.SupplierData = data.data.rows
      },
      async Wms_planGetDetailPageData() {
        const params = {
          pageNo: 1,
          pageSize: 100,
          total: 0,
          tableName: '',
          sort: '',
          order: '',
          wheres: '',
          export: true,
          value: this.IPMID,
        }
        const data = await Wms_planGetDetailPageData(params)
        if (data.master) {
          this.$nextTick(() => {
            this.chileddetail = data.rows
          })
        }
        console.log(data)
      },
      async AddData() {
        this.isclick = true
        const params = {
          mainData: this.form,
          detailData: this.chileddetail,
          delKeys: [],
        }
        const data = await Wms_planAddData(params)
        if (data.code == '200') {
          this.getList()
          this.$message({
            message: translate('保存成功'),
            type: 'success',
          })
          this.dialogVisible = false
        }
        setTimeout(() => {
          this.isclick = false
        }, 5000)
      },
      async updataSaveList() {
        const params = {
          mainData: this.form,
          detailData: this.chileddetail,
          delKeys: this.deleList,
        }
        const data = await Wms_planUpdateData(params)
        if (data.code == '200') {
          this.getList()
          this.$message({
            message: translate('保存成功'),
            type: 'success',
          })
          this.dialogVisible = false
        }
      },
    },
  })
</script>
<style lang="scss" scoped>
  .flowpath-container {
    .color_494949 {
      color: #494949;
    }
    .w164 {
      width: 164px;
    }
    .mb20 {
      margin-bottom: 20px;
    }
    .mr10 {
      margin-right: 10px;
    }

    .iconcommon {
      position: absolute;
      top: 80px;
      right: 70px;
      font-size: 60px;
      color: blue;
    }
    .iconcommon2 {
      position: absolute;
      top: 80px;
      right: 70px;
      font-size: 60px;
      color: red;
    }
    .add {
      margin-bottom: 10px;
      text-align: left;
    }
    .iconcolor {
      color: #409eff;
    }
  }
</style>
